﻿using System;
using System.Data;
using Tyche.Common.Resource;
using Tyche.DAO.Mapper;

namespace Tyche.DAO.Transaction
{
    public class TycheTransaction
    {
        /// <summary>
        /// Mapper
        /// </summary>
        private ITycheMapper mapper;

        /// <summary>
        /// DbTransaction
        /// </summary>
        private IDbTransaction dbTransaction;

        /// <summary>
        /// Level
        /// </summary>
        private IsolationLevel level;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="level"></param>
        public TycheTransaction(IsolationLevel level)
        {
            this.level = level;
        }

        /// <summary>
        /// 创建Mapper
        /// </summary>
        /// <returns></returns>
        public ITycheMapper CreateMapper()
        {
            if (mapper == null)
            {
                mapper = (ITycheMapper)Activator.CreateInstance(TycheResourceManager.GetResource<ITycheMapper>().Implement, new object[] { });
            }

            return mapper;
        }

        /// <summary>
        /// 开启事务
        /// </summary>
        public IDbTransaction BeginTransaction()
        {
            if (dbTransaction == null)
            {
                dbTransaction = mapper.BeginTransaction(level);
            }

            return dbTransaction;
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            dbTransaction.Dispose();
            mapper.Dispose();

            TycheTransactionManager.Dispose();
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        public void Commit()
        {
            if (mapper != null && dbTransaction != null)
            {
                dbTransaction.Commit();
                Dispose();
            }
        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        public void RollBack()
        {
            if (mapper != null && dbTransaction != null)
            {
                dbTransaction.Rollback();
                Dispose();
            }
        }
    }
}
